<?php
namespace Components\User\Sha\Mutually\Buy;

use Components\User\Sha\Auth;
use Components\User\Sha\Service as UserService;
use Components\User\Sha\Wallet\Service as UserWalletService;
use Components\User\Sha\Validation as UserValidation;
use Components\User\Sha\Wallet\Record\Dynamic99181Model;

class Facade {
  public function updateStatusByToken($token, $id, $status, $data) {
    $checkToken = Auth::checkToken($token);
    if($checkToken['code'] != 0) { return $checkToken; }

    $resUser = (new UserService()) -> findFirst(['conditions'=>'id = '.$checkToken['payload']['user']['id']]);
    if($resUser['code'] != 0) { return $resUser; }
    $checkSafePassword = (new UserValidation()) -> checkSafePassword($data['safe_password'], $resUser['model'] -> safe_password);
    if($checkSafePassword['code'] != 0) { return ['code'=>$checkSafePassword['code'],'msg'=>'安全密码错误']; }

    return (new Logic()) -> updateStatus($id, $status, $data);
  }

  public function updateResetMatchByToken($token, $id) {
    $checkToken = Auth::checkToken($token);
    if($checkToken['code'] != 0) { return $checkToken; }

    $userWallet = (new UserWalletService()) -> findFirstById($checkToken['payload']['user']['id']);
    if($userWallet['code'] != 0) { return $userWallet; }

    if($userWallet['model'] -> appointment < 1) { return ['code'=>-1,'msg'=>'预约币不足']; }

    $currentTime = time();
    $averageModel = AverageModel::findFirst([
      'conditions' => 'id = ' . $id
    ]);
    $averageModel -> match_time = $currentTime;
    $averageModel -> reset_match += 1;

    $userWalletAppointmentRecord = new \Components\User\Sha\Wallet\Record\AppointmentModel([
      'user_id' => $userWallet['model'] -> user_id,
      'type' => 17106,
      'action' => 45,
      'amount' => 1,
      'amount_old' => $userWallet['model'] -> appointment,
      'create_time' => $currentTime,
      'remark' => '使用'
    ]);

    $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();

    try {
      $userWallet['model'] -> appointment -= 1;
      $userWallet['model'] -> setTransaction($transaction);
      if(!$userWallet['model'] -> update()) {
        $msgs = $userWallet['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $userWalletAppointmentRecord -> amount_new = $userWallet['model'] -> appointment;
      $userWalletAppointmentRecord -> setTransaction($transaction);
      if(!$userWalletAppointmentRecord -> create()) {
        $msgs = $userWalletAppointmentRecord['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $averageModel -> setTransaction($transaction);
      if(!$averageModel -> update()) {
        $msgs = $averageModel['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }
      
      $transaction -> commit();
    } catch(\Exception $e) {
      return ['code' => -1, 'msg' => $e -> getMessage()];
    }

    return ['code' => 0, 'msg' => '延时成功', 'user_wallet' => $userWallet['model']];
  }

  public function findFirstByIdAndToken($id, $token) {
    $checkToken = Auth::checkToken($token);
    if($checkToken['code'] != 0) { return $checkToken; }

    return (new Logic()) -> findFirstById($id);
  }

  protected function pagerQuery($query) {
    if(!isset($query['page'])) {
      $query['page'] = 1;
    } else if($query['page'] <= 0)  {
      $query['page'] = 1;
    } else {
      $query['page'] = abs($query['page']);
    }

    if(!isset($query['limit'])) {
      $query['limit'] = 10;
    } else if($query['limit'] <= 0)  {
      $query['limit'] = 10;
    } else {
      $query['limit'] = abs($query['limit']);
    }

    return $query;
  }

  public function pagerByToken($token, $query) {
    $checkToken = Auth::checkToken($token);
    if($checkToken['code'] != 0) { return $checkToken; }

    $query = $this -> pagerQuery($query);
    $parameters['conditions']['user'] = ['id' => $checkToken['payload']['user']['id']];
    return (new Logic()) -> pagerUseParameters($query['limit'], $query['page'], $parameters);
  }

  public function pager($query) {
    $query = $this -> pagerQuery($query);
    return (new Logic()) -> pager($query['limit'], $query['page']);
  }

  public function createByTokenAndField($fields_index, $token, $data) {
    $checkToken = Auth::checkToken($token);
    if($checkToken['code'] != 0) { return $checkToken; }

    $resUser = (new UserService()) -> findFirst(['conditions'=>'id = '.$checkToken['payload']['user']['id']]);
    if($resUser['code'] != 0) { return $resUser; }

    $checkSafePassword = (new UserValidation()) -> checkSafePassword($data['safe_password'], $resUser['model'] -> safe_password);
    if($checkSafePassword['code'] != 0) { return ['code'=>$checkSafePassword['code'],'msg'=>'安全密码错误']; }

    $parameters = \Phalcon\Di::getDefault() -> getShared('parameters') -> getSharedFactory() -> getFacade() -> findByKeyUseCacheIsDisabled();
    $USER_MUTUALLY_BUY_STATIC = $parameters[$data['parameters']];
    $USER_MUTUALLY_BUY_STATIC_value = $USER_MUTUALLY_BUY_STATIC['value'][$data['parameters_key']]['value'];

    $USER_MUTUALLY_BUY_STATIC_WAITING_DAY = $parameters['USER_MUTUALLY_BUY_STATIC_WAITING_DAY'];

    if($data['amount'] != $USER_MUTUALLY_BUY_STATIC_value['amount']) { return ['code'=>-1,'msg'=>'数量与模式不一致']; }

    $lastMutuallyBuyModel = Model::findFirst([
      'conditions' => 'user_id = ' . $resUser['model'] -> id,
      'order' => 'id DESC'
    ]);

    $loopNumber = 1;
    $isLoopNumber = 0;
    $currentTime = time();
    if($lastMutuallyBuyModel) {
      if(
        $lastMutuallyBuyModel -> status != 80 &&
        $lastMutuallyBuyModel -> status != 90
      ) { return ['code'=>-1,'msg'=>'请等候上一单匹配完成']; }

      $lastAverageModel = AverageModel::findFirst([
        'conditions' => 'user_mutually_buy_id = ' . $lastMutuallyBuyModel -> id,
        'order' => 'id DESC'
      ]);
      if(
        $lastAverageModel -> status != 80 &&
        $lastAverageModel -> status != 90
      ) { return ['code'=>-1,'msg'=>'请等候上一单匹配完成']; }

      $loopNumber += $lastMutuallyBuyModel -> loop_number;
      if($lastMutuallyBuyModel -> loop_number % 2 == 0 && $loopNumber < 10) {
        if(($lastAverageModel -> create_time + ($USER_MUTUALLY_BUY_STATIC_WAITING_DAY['value'] * 24 * 60 * 60)) > $currentTime) {
          return ['code'=>-1,'msg'=>'请等候' . $USER_MUTUALLY_BUY_STATIC_WAITING_DAY['value'] . '天后才能再次匹配.'];
        }
      }

    } else if($resUser['model'] -> pid != 0) {
      $isLoopNumber = 1;
      $dynamic99181Model = new Dynamic99181Model([
        'from_user_id' => $resUser['model'] -> id,
        'to_user_id' => $resUser['model'] -> pid,
        'amount' => 2000,
        'original_amount' => 2000,
        'average' => 10,
        'create_time' => $currentTime
      ]);
    }

    if($isLoopNumber === 1 && $loopNumber > 5) {
      $loopNumber = 1;
    } else if($loopNumber > 3) {
      $loopNumber = 1;
    }
    
    $mutuallyBuyModel = new Model([
      'user_id' => $resUser['model'] -> id,
      'field' => $fields_index,
      'amount' => $USER_MUTUALLY_BUY_STATIC_value['amount'],
      'average' => $USER_MUTUALLY_BUY_STATIC_value['average'],
      'create_time' => $currentTime,
      'loop_number' => $loopNumber,
      'is_loop_number' => $isLoopNumber
      'status' => 20
    ]);

    $mutuallyBuyAverageData = [
      'user_id' => $resUser['model'] -> id,
      'user_mutually_sell_average_id' => 0,
      'status' => 10,
      'create_time' => $currentTime
    ];

    $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();

    try {
      $mutuallyBuyModel -> setTransaction($transaction);
      if(!$mutuallyBuyModel -> create()) {
        $msgs = $mutuallyBuyModel -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      if(isset($dynamic99181Model)) {
        $dynamic99181Model -> setTransaction($transaction);
        if(!$dynamic99181Model -> create()) {
          $msgs = $dynamic99181Model -> getMessages();
          $transaction -> rollback($msgs[0] -> getMessage());
        }
      }

      $mutuallyBuyAverageData['user_mutually_buy_id'] = $mutuallyBuyModel -> id;
      if($loopNumber % 2 == 0) {
        $mutuallyBuyAverageData['average_index'] = 1;
        $mutuallyBuyAverageData['amount'] = $mutuallyBuyModel -> amount / $mutuallyBuyModel -> average;
        $averageModel = new AverageModel($mutuallyBuyAverageData);
        $averageModel -> setTransaction($transaction);
        if(!$averageModel -> create()) {
          $msgs = $averageModel -> getMessages();
          $transaction -> rollback($msgs[0] -> getMessage());
        }
      } else {
        for($i=1;$i<=$mutuallyBuyModel -> average;$i++) {
          $mutuallyBuyAverageData['average_index'] = $i;
          $mutuallyBuyAverageData['amount'] = $mutuallyBuyModel -> amount / $mutuallyBuyModel -> average;
          $averageModel = new AverageModel($mutuallyBuyAverageData);
          $averageModel -> setTransaction($transaction);
          if(!$averageModel -> create()) {
            $msgs = $averageModel -> getMessages();
            $transaction -> rollback($msgs[0] -> getMessage());
          }
        }
      }

      $resUser['model'] -> mutually_buy_total += 1;
      $resUser['model'] -> update();

      $transaction -> commit();
    } catch(\Exception $e) {
      return ['code' => -1, 'msg' => $e -> getMessage()];
    }

    return ['code' => 0, 'msg' => '排单成功'];
  }
}
